//
//  CompanyInfoVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2020/8/31.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "CompanyInfoVC.h"
#import "CompanyInfoInPutCell.h"
#import "CompanyInfoModel.h"
#import "CompanyInfoImgCell.h"

@interface CompanyInfoVC () <UITableViewDelegate,UITableViewDataSource,TZImagePickerControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) CompanyInfoModel *model;

@end

@implementation CompanyInfoVC

-(CompanyInfoModel *)model {
    if (!_model) {
        _model = [CompanyInfoModel new];
    }
    return _model;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - 64 - BottomHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - BottomHeight - NaviHeight - 64, ScreenW, 64+BottomHeight)];
        _bottomView.backgroundColor = HexColor(0xffffff);
        
        UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, ScreenW - 60, 44)];
        [saveBtn setBackgroundColor:Color_ThemeColor];
        saveBtn.layer.masksToBounds = YES;
        saveBtn.layer.cornerRadius = 6;
        [saveBtn setTitle:@"保存" forState:0];
        [saveBtn setTitleColor:HexColor(0xffffff) forState:0];
        saveBtn.titleLabel.font = BoldFontOfSize(16);
        [saveBtn addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:saveBtn];
    }
    return _bottomView;
}

- (void)saveClick {
    NSMutableDictionary *dic= [ NSMutableDictionary dictionary];
    if (self.model.company_name.length) {
        [dic setObject:self.model.company_name forKey:@"company_name"];
    }
    if (self.model.update_licenseimg.length) {
        [dic setObject:self.model.update_licenseimg forKey:@"license"];
    }
    if (self.model.tel.length) {
        [dic setObject:self.model.tel forKey:@"tel"];
    }
    if (self.model.address.length) {
        [dic setObject:self.model.address forKey:@"address"];
    }
    if (self.model.account_bank.length) {
        [dic setObject:self.model.account_bank forKey:@"account_bank"];
    }
    if (self.model.bank_card.length) {
        [dic setObject:self.model.bank_card forKey:@"bank_card"];
    }
    if (self.model.tax_num.length) {
        [dic setObject:self.model.tax_num forKey:@"tax_num"];
    }
    [HttpRequest PostWithApi:LogisticsSupplierModifyCompanyInfo params:dic progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            __weak_self;
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"保存成功" delayOperation:^{
                [weakself.rt_navigationController popViewControllerAnimated:YES];
            }];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"企业信息";
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self requestForInfo];
}

- (void)requestForInfo {
    [HttpRequest PostWithApi:LogisticsSupplierGetCompanyInfo params:@{} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.model = [CompanyInfoModel mj_objectWithKeyValues:responseObject];
            [self.tableView reloadData];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 8;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CompanyInfoInPutCell *cell = [CompanyInfoInPutCell CompanyInfoInPutCellWithTableView:tableView];
    if (indexPath.row == 0) {
        cell.titleText = @"企业编号";
        cell.showLine = YES;
        cell.canClick = NO;
        cell.isMust = NO;
        cell.isCanNoEdit = YES;
        cell.contentText = self.model.company_no;
//        __weak_self;
//        cell.cellBlock = ^(NSString * _Nonnull str) {
//            weakself.model.company_no = str;
//        };
    }else if (indexPath.row == 1) {
        cell.titleText = @"公司名称";
        cell.showLine = YES;
        cell.canClick = NO;
        cell.isMust = NO;
        cell.contentText = self.model.company_name;
        __weak_self;
        cell.cellBlock = ^(NSString * _Nonnull str) {
            weakself.model.company_name = str;
        };
    }else if (indexPath.row == 2) {
        CompanyInfoImgCell *cell = [CompanyInfoImgCell CompanyInfoImgCellWithTableView:tableView];
        cell.titleText = @"营业执照";
        cell.showLine = YES;
        cell.isMust = NO;
        cell.canClick = YES;
        cell.iconUrl = self.model.licenseimg;
        __weak_self;
        cell.clickBlock = ^{
            [weakself chooseImg];
        };
        return cell;
    }else if (indexPath.row == 3) {
        cell.titleText = @"电话号码";
        cell.showLine = YES;
        cell.canClick = NO;
        cell.isMust = NO;
        cell.contentText = self.model.tel;
        __weak_self;
        cell.cellBlock = ^(NSString * _Nonnull str) {
            weakself.model.tel = str;
        };
    }else if (indexPath.row == 4) {
        cell.titleText = @"税号";
        cell.showLine = YES;
        cell.canClick = NO;
        cell.isMust = NO;
        cell.contentText = self.model.tax_num;
        __weak_self;
        cell.cellBlock = ^(NSString * _Nonnull str) {
            weakself.model.tax_num = str;
        };
    }else if (indexPath.row == 5) {
        cell.titleText = @"单位地址";
        cell.showLine = YES;
        cell.canClick = NO;
        cell.isMust = NO;
        cell.contentText = self.model.address;
        __weak_self;
        cell.cellBlock = ^(NSString * _Nonnull str) {
            weakself.model.address = str;
        };
    }else if (indexPath.row == 6) {
        cell.titleText = @"开户行";
        cell.showLine = YES;
        cell.canClick = NO;
        cell.isMust = NO;
        cell.contentText = self.model.account_bank;
        __weak_self;
        cell.cellBlock = ^(NSString * _Nonnull str) {
            weakself.model.account_bank = str;
        };
    }else if (indexPath.row == 7) {
        cell.titleText = @"银行账号";
        cell.showLine = NO;
        cell.canClick = NO;
        cell.isMust = NO;
        cell.contentText = self.model.bank_card;
        __weak_self;
        cell.cellBlock = ^(NSString * _Nonnull str) {
            weakself.model.bank_card = str;
        };
    }
    return cell;
}

- (void)chooseImg {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:1 delegate:self pushPhotoPickerVc:YES];
        imagePickerVc.isSelectOriginalPhoto = YES;
        imagePickerVc.allowTakeVideo = NO;   // 在内部显示拍视频按
        imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
        imagePickerVc.showPhotoCannotSelectLayer = YES;
        imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
        [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
            [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }];
        // 你可以通过block或者代理，来得到用户选择的照片.
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            //通过asset获取原图，方法会先返回缩略图，再返回原图
//            [[TZImageManager manager] getOriginalPhotoWithAsset:assets.firstObject newCompletion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
//                if ([info[PHImageResultIsDegradedKey] boolValue]) {
//                    //返回的是缩略图
//                }else {
//                    //返回的是原图
//                    [self requestForUpload:photo];
//                }
//            }];
            [[TZImageManager manager] getOriginalPhotoDataWithAsset:assets.firstObject progressHandler:^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
                
            } completion:^(NSData *data, NSDictionary *info, BOOL isDegraded) {
                [self requestForUpload:data];
            }];
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)requestForUpload:(NSData *)image {
    [MBProgressHUD leShowHUDWithMessage:@"上传中" activity:YES];
    [HttpRequest postImgDataWithUrl:LogisticsSupplierUploadImg imgData:image imgFile:@"file" withParameter:@{@"type":@(1)} sucess:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.model.licenseimg = [NSString stringWithFormat:@"%@%@",[responseObject objectForKey:@"url"],[responseObject objectForKey:@"path"]];
            self.model.update_licenseimg = [responseObject objectForKey:@"path"];
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
//    [HttpRequest postImgWithUrl:LogisticsSupplierUploadImg imglist:@[image] imgFile:@"file" withParameter:@{@"type":@(1)} sucess:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
//        if (code) {
//            self.model.licenseimg = [NSString stringWithFormat:@"%@%@",[responseObject objectForKey:@"url"],[responseObject objectForKey:@"path"]];
//            self.model.update_licenseimg = [responseObject objectForKey:@"path"];
//            [self.tableView reloadData];
//        }
//    } failure:^(NSError * _Nonnull error) {
//
//    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 2) {
        CompanyInfoImgCell *cell = [CompanyInfoImgCell CompanyInfoImgCellWithTableView:tableView];
        return cell.height;
    }
    CompanyInfoInPutCell *cell = [CompanyInfoInPutCell CompanyInfoInPutCellWithTableView:tableView];
    return cell.height;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = Color_backgroundColor;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 2) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
        view.backgroundColor = Color_backgroundColor;
        return view;
    }
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 2) {
        return 10;
    }
    return 0;
}

@end
